import axios from 'axios'
import store from '@/store'
import router from '@/router'
import { setSession, getSession, setUserInfo, getUserInfo } from '@/utils/auth'
import { parseDate, dateAddDays } from '@/utils'

const baseUrl = "http://daisoft.duia.eu:30459"  // http://localhost:3000/api  http://daisoft.duia.eu:30459  https://daisoft.duia.eu:27003/
const baseDBName = 'MesTest'  //Dev:MesTest   Prd:shretec

//登陆
export function loginToSAP(config){
  return new Promise((resolve,reject)=>{
      const {username, password} = config
      var fmData = new FormData();
      fmData.append('name',username)
      fmData.append('pwd',password)

      axios({
        method: "post",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        url: (baseDBName == 'MesTest' ? baseUrl : '') + "/api/Login",  //baseUrl+
        data: fmData,
      }).then(res => {
        console.log('loginToSAP-------!!',res);
        //PRD: statusText===''   DEV: statusText==='OK'
        if(res.status===200 && (res.statusText==='OK' || res.statusText==='')){
          const _session = Object.keys(res.data)
          if(_session.length === 1){
            setSession(_session[0])
            const _userInfo = res.data[_session]
            setUserInfo(_userInfo)
            console.log('successfully submit!!', _session, _userInfo);
            resolve(_userInfo)
          }
        }
      }).catch(err=> {
        console.log('error submit!!',err);
        reject(err.response)
      });
  })
}

//获取熟化 / 分切工程当日待生产的批次
export function getWaitingProdList(config){
  return new Promise((resolve,reject)=>{
     const { U_Ostate } = config
      var fmData = new FormData();
      fmData.append('U_Ostate',U_Ostate)
      fmData.append('_session',getSession())

      axios({
        method: "post",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        url: (baseDBName == 'MesTest' ? baseUrl : '') + '/api/Query?_db='+baseDBName+"&_xkey=srd_homefun", //baseUrl+   
        data: fmData,
      }).then(res => {
        console.log('getSHWaitingProdList-------!!',res);
        //PRD: statusText===''   DEV: statusText==='OK'
        if(res.status===200 && (res.statusText==='OK' || res.statusText==='')){
          resolve(res.data)
        }else{
          resolve([])
        }
      }).catch(err=> {
        console.log('error submit!!',err);
        reject(err.response)
      });
  })
}

//获取指定设备的最后一次操作明细
export function getLastMPCPByResID(config){
  return new Promise((resolve,reject)=>{
     const { ResId } = config
      var fmData = new FormData();
      fmData.append('ResId',ResId)
      fmData.append('_session',getSession())

      axios({
        method: "post",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        url: (baseDBName == 'MesTest' ? baseUrl : '') + '/api/Query?_db='+baseDBName+"&_xkey=srd_homefun1",  //baseUrl+
        data: fmData,
      }).then(res => {
        if(res.status===200 && (res.statusText==='OK' || res.statusText==='')){
          resolve(res.data)
        }else{
          resolve([])
        }
      }).catch(err=> {
        console.log('error submit!!',err);
        reject(err.response)
      });
  })
}

//查询指定时间内所有MPCP操作记录
export function getAllMPCPLists(config){
  return new Promise((resolve,reject)=>{
     const { from, to, Canceled='', MEQG = '', MEQU= '',MPCO= '' } = config
      var fmData = new FormData();
      fmData.append('_session',getSession())
      fmData.append('from',from)
      fmData.append('to',to)
      fmData.append('Canceled',Canceled.trim())
      fmData.append('MEQG',MEQG.trim())
      fmData.append('MEQU',MEQU.trim())
      fmData.append('MPCO',MPCO.trim())
      axios({
        method: "post",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        url: (baseDBName == 'MesTest' ? baseUrl : '') + '/api/Query?_db='+baseDBName+"&_xkey=srd_lotexec", //baseUrl+
        data: fmData,
      }).then(res => {
        if(res.status===200 && (res.statusText==='OK' || res.statusText==='')){
          resolve(res.data)
        }else{
          resolve([])
        }
      }).catch(err=> {
        console.log('error submit!!',err);
        reject(err.response)
      });
  })
}

//查询指定时间内所有MPCP操作记录（包含生产/质量数据）
export function getAllMPCPendDataLists(config){
  return new Promise((resolve,reject)=>{
     const { from, to, Canceled='', MEQG = '', MEQU= '',MPCO= '' } = config
      var fmData = new FormData();
      fmData.append('_session',getSession())
      fmData.append('from',from)
      fmData.append('to',to)
      fmData.append('Canceled',Canceled.trim())
      fmData.append('MEQG',MEQG.trim())
      fmData.append('MEQU',MEQU.trim())
      fmData.append('MPCO','end')
      axios({
        method: "post",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        url: (baseDBName == 'MesTest' ? baseUrl : '') + '/api/Query?_db='+baseDBName+"&_xkey=srd_sczldata",  //baseUrl+
        data: fmData,
      }).then(res => {
        if(res.status===200 && (res.statusText==='OK' || res.statusText==='')){
          resolve(res.data)
        }else{
          resolve([])
        }
      }).catch(err=> {
        console.log('error submit!!',err);
        reject(err.response)
      });
  })
}

//查询生产/质检明细数据
export function getAllProductDataLists(config){
  return new Promise((resolve,reject)=>{
     const { from, to, BOUDF='', MEQU= '' } = config
     var cols = []

     fetchCommonList({
       'fields':'LineId,U_Fd,U_FdType,U_Decim,U_IsReq,U_VisOrder',
       'table':'@BOUDF1',
       'page': 1,
       'limit': 99999,
       'eq_Code': BOUDF,
       'orderby':'LineId'
     }).then(res=>{
        cols = res.data.sort((a,b)=>a.U_VisOrder.localeCompare(b.U_VisOrder))

        var fmData = new FormData();
        fmData.append('_session',getSession())
        fmData.append('from',from)
        fmData.append('to',to)
        fmData.append('BOUDF',BOUDF.trim())
        fmData.append('MEQU',MEQU.trim())
        axios({
          method: "post",
          headers: {"Content-Type": "application/x-www-form-urlencoded"},
          url: (baseDBName == 'MesTest' ? baseUrl : '') + '/api/Query?_db='+baseDBName+"&_xkey=srd_lotdata", //baseUrl+
          data: fmData,
        }).then(res => {
          if(res.status===200 && (res.statusText==='OK' || res.statusText==='')){
            resolve({'list':res.data,'cols':cols})
          }else{
            resolve({'list':[],'cols':cols})
          }
        }).catch(err=> {
          console.log('error submit!!',err);
          reject(err.response)
        });

     }).catch(err=> {
        console.log('error submit!!',err);
        reject(err.response)
      });

  })
}


//新增或更新 生产数据或质检数据模板
export function updateBOUDFs(config) {
  return new Promise((resolve,reject)=>{
    var { DocEntry = '', Code, LineId, U_Fd, U_FdType, U_IsReq, U_VisOrder, isNew = false } = config
    var _key = Code

    if(isNew){
      fetchCommonList({
        'fields':'Code,LineId,U_Fd,U_FdType,U_Rlist,U_Rtable,U_Decim,U_IsReq,U_VisOrder',
        'table':'@BOUDF1',
        'page': 1,
        'limit': 2000,
        'eq_Code': Code
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.filter(item=>item.Code == Code).sort((a,b)=>a.U_VisOrder.localeCompare(b.U_VisOrder))
          console.log('_list--------',Code,_list)

          const _lastVisOrder = _list[_list.length - 1].U_VisOrder
          U_VisOrder = _lastVisOrder.substr(0, 1) + (_lastVisOrder.substr(1, _lastVisOrder.length - 1) * 1 + 1)
            .toString().padStart(3, '0')

          console.log('addTheNewField---------',config)
        }

        var _tables = '<BOUDF><BOUDF1>'

        if(DocEntry == ''){
          _tables += '<row><U_Fd>'+U_Fd+'</U_Fd><U_FdType>'+U_FdType+'</U_FdType><U_IsReq>'+U_IsReq+'</U_IsReq><U_VisOrder>'+U_VisOrder+'</U_VisOrder></row>'
        }else{
          _tables += '<row lineid=\"'+ LineId +'\"><U_Fd>'+U_Fd+'</U_Fd><U_FdType>'+U_FdType+'</U_FdType><U_IsReq>'+U_IsReq+'</U_IsReq><U_VisOrder>'+U_VisOrder+'</U_VisOrder></row>'
        }
        _tables += '</BOUDF1></BOUDF>'

        updateCommonDao({
          'id':'U1',
          'tables':encodeURIComponent(_tables),
          'key': _key
        }).then(res=>{
          resolve(res)
        }).catch(err=> {
          reject(err)
        });

      }).catch(err=> {
        reject(err)
      });

    }else{

      var _tables = '<BOUDF><BOUDF1>'

      if(DocEntry == ''){
        _tables += '<row><U_Fd>'+U_Fd+'</U_Fd><U_FdType>'+U_FdType+'</U_FdType><U_IsReq>'+U_IsReq+'</U_IsReq><U_VisOrder>'+U_VisOrder+'</U_VisOrder></row>'
      }else{
        _tables += '<row lineid=\"'+ LineId +'\"><U_Fd>'+U_Fd+'</U_Fd><U_FdType>'+U_FdType+'</U_FdType><U_IsReq>'+U_IsReq+'</U_IsReq><U_VisOrder>'+U_VisOrder+'</U_VisOrder></row>'
      }
      _tables += '</BOUDF1></BOUDF>'

      updateCommonDao({
        'id':'U1',
        'tables':encodeURIComponent(_tables),
        'key': _key
      }).then(res=>{
        resolve(res)
      }).catch(err=> {
        reject(err)
      });

    }


  })
}

export function updateBOUDFLocations(config) {
  return new Promise((resolve,reject)=>{
    const { Code, LineId1, VisOrder1, LineId2, VisOrder2 } = config
    var _key = Code

    var _tables = '<BOUDF><BOUDF1>'

    _tables += '<row lineid=\"'+ LineId1 +'\"><U_VisOrder>'+VisOrder1+'</U_VisOrder></row>'
    _tables += '<row lineid=\"'+ LineId2 +'\"><U_VisOrder>'+VisOrder2+'</U_VisOrder></row>'
    _tables += '</BOUDF1></BOUDF>'

    updateCommonDao({
      'id':'U1',
      'tables':encodeURIComponent(_tables),
      'key': _key
    }).then(res=>{
      resolve(res)
    }).catch(err=> {
      reject(err)
    });

  })
}

export function deleteBOUDFByLineId(config) {
  return new Promise((resolve,reject)=>{
    const { Code, LineId, U_Fd, U_FdType, U_IsReq, U_VisOrder } = config
    var _key = Code

    var _tables = '<BOUDF><BOUDF1><row lineid=\"'+ LineId +'\" delrow=\"1\"><U_Fd>'+U_Fd+'</U_Fd><U_FdType>'+U_FdType+'</U_FdType><U_IsReq>'+U_IsReq+'</U_IsReq><U_VisOrder>'+U_VisOrder+'</U_VisOrder></row></BOUDF1></BOUDF>'

    updateCommonDao({
      'id':'U1',
      'tables':encodeURIComponent(_tables),
      'key': _key
    }).then(res=>{
      resolve(res)
    }).catch(err=> {
      reject(err)
    });

  })
}

//新增或更新 生产数据或质检数据 (当前U_RefCode取MPCP1中第一行记录中的批次号码)
export function updateBOUDDs(config) {
  return new Promise((resolve,reject)=>{
    const { DocEntry, U_RefEntry, U_RefType, U_BOUDF, list} = config
    var _key = DocEntry

    fetchCommonList({
      'fields':'DocEntry,LineId,U_MLOO',
      'table':'@MPCP1',
      'page': 1,
      'limit': 9999,
      'eq_DocEntry': U_RefEntry,
      'orderby':'LineId'
    }).then(resData=>{
      if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
        var _U_MLOO = resData.data.length>0 ? resData.data[0].U_MLOO : ''
        var _tables = '<BOUDD><U_BOUDF>'+U_BOUDF+'</U_BOUDF><U_RefCode>'+_U_MLOO+'</U_RefCode><U_RefEntry>'+U_RefEntry+'</U_RefEntry><U_RefType>'+U_RefType+'</U_RefType><BOUDD1>'

        var _tmpFdType = ''
        if(DocEntry == ''){
          list.forEach(item=>{
            _tmpFdType = (item.U_FdType == 'B1' || item.U_FdType == 'B2') ? 'B' : item.U_FdType
            _tables += '<row><U_Fd>'+item.U_Fd+'</U_Fd><U_'+_tmpFdType+'>'+item.val+'</U_'+_tmpFdType+'></row>'
          })
        }else{
          list.forEach(item=>{
            _tmpFdType = (item.U_FdType == 'B1' || item.U_FdType == 'B2') ? 'B' : item.U_FdType
            _tables += '<row lineid=\"'+ item.LineId +'\"><U_Fd>'+item.U_Fd+'</U_Fd><U_'+_tmpFdType+'>'+item.val+'</U_'+_tmpFdType+'></row>'
          })
        }
        _tables += '</BOUDD1></BOUDD>'

        updateCommonDao({
          'id':'U2',
          'tables':encodeURIComponent(_tables),
          'key': _key
        }).then(res=>{
          resolve(res)
        }).catch(err=> {
          reject(err)
        });

      }
    }).catch(err=>{
      reject(err)
    })

  })
}

// export function updateBOUDDs(config) {
//   return new Promise((resolve,reject)=>{
//     const { DocEntry, U_RefCode, U_BOUDF, list} = config
//     var _key = DocEntry
//     var _tables = '<BOUDD><U_BOUDF>'+U_BOUDF+'</U_BOUDF><U_RefCode>'+U_RefCode+'</U_RefCode><U_RefEntry>'+U_RefCode+'</U_RefEntry><U_RefType>MPCP</U_RefType><BOUDD1>'

//     if(DocEntry == ''){
//       list.forEach(item=>{
//         _tables += '<row><U_Fd>'+item.U_Fd+'</U_Fd><U_'+item.U_FdType+'>'+item.val+'</U_'+item.U_FdType+'></row>'
//       })
//     }else{
//       list.forEach(item=>{
//         _tables += '<row lineid=\"'+ item.LineId +'\"><U_Fd>'+item.U_Fd+'</U_Fd><U_'+item.U_FdType+'>'+item.val+'</U_'+item.U_FdType+'></row>'
//       })
//     }
//     _tables += '</BOUDD1></BOUDD>'

//     updateCommonDao({
//       'id':'U2',
//       'tables':encodeURIComponent(_tables),
//       'key': _key
//     }).then(res=>{
//       resolve(res)
//     }).catch(err=> {
//       reject(err)
//     });

//   })
// }

//更新用户组(名称和权限)
export function updateBOUSGs(config) {
  return new Promise((resolve,reject)=>{
    const { DocEntry, Code='', Name, U_Menu} = config
    var _tables = ''
    var _key = ''
    if(DocEntry==undefined || DocEntry==''){
      _tables = '<BOUSG><Code>'+Code+'</Code><Name>'+Name+'</Name><U_Menu>'+U_Menu+'</U_Menu></BOUSG>'
      _key = ''
    }else{
      _tables = '<BOUSG><Name>'+Name+'</Name><U_Menu>'+U_Menu+'</U_Menu></BOUSG>'
      _key = Code
    }
      updateCommonDao({
        'id':'U1',
        'tables':encodeURIComponent(_tables),
        'key': _key
      }).then(res=>{
        resolve(res)
      }).catch(err=> {
        reject(err)
      });

  })
}

//更新用户(名称和用户组)
export function updateBOUSRs(config) {
  return new Promise((resolve,reject)=>{
    const { DocEntry, Code='', Name, U_BOUSG, U_Pwd} = config
    var _tables = ''
    var _key = ''
    if(DocEntry==undefined || DocEntry==''){
      _tables = '<BOUSR><Code>'+Code+'</Code><Name>'+Name+'</Name><U_BOUSG>'+U_BOUSG+'</U_BOUSG><U_Pwd>1234</U_Pwd></BOUSR>'
      _key = ''
    }else{
      _tables = '<BOUSR><Name>'+Name+'</Name><U_BOUSG>'+U_BOUSG+'</U_BOUSG></BOUSR>'
      _key = Code
    }
      updateCommonDao({
        'id':'U1',
        'tables':encodeURIComponent(_tables),
        'key': _key
      }).then(res=>{
        resolve(res)
      }).catch(err=> {
        reject(err)
      });

  })
}

//更新用户密码
export function updateUserPasswordBOUSRs(config) {
  return new Promise((resolve,reject)=>{
    const { Code , U_Pwd} = config
    var _tables = '<BOUSR><U_Pwd>'+U_Pwd+'</U_Pwd></BOUSR>'
    var _key = Code

    updateCommonDao({
      'id':'U1',
      'tables':encodeURIComponent(_tables),
      'key': _key
    }).then(res=>{
      resolve(res)
    }).catch(err=> {
      reject(err)
    });

  })
}

//更新指定设备信息(名称和启用/停用)
export function updateMEQUs(config) {
  return new Promise((resolve,reject)=>{
    const { DocEntry, Code, Name='', Canceled='N'} = config
    var _tables = '<MEQU><Name>'+Name+'</Name></MEQU>'    //<Canceled>'+Canceled+'</Canceled>

    updateCommonDao({
      'id':'U1',
      'tables':encodeURIComponent(_tables),
      'key': Code
    }).then(res=>{
      resolve(res)
    }).catch(err=> {
      reject(err)
    });

  })
}

export function updateMEQUEnableOrDisable(config) {
  return new Promise((resolve,reject)=>{
    const { Code, Status} = config

    var _tables = (Status == 'on') ? '<MEQU>K</MEQU>' : '<MEQU>C</MEQU>'

    updateCommonDao({
      'id':'U1',
      'tables':encodeURIComponent(_tables),
      'key': Code
    }).then(res=>{
      resolve(res)
    }).catch(err=> {
      reject(err)
    });

  })
}

//工程逆处理
export function processBacktoPreviousMPCPs(config) {
  return new Promise((resolve,reject)=>{
    const { key} = config
    console.log('processBacktoPreviousMPCPs receive para:',key)
      updateCommonDao({
        'id':'U2',
        'tables':encodeURIComponent('<MPCP>C</MPCP>'),
        'key': key
      }).then(res=>{
        resolve(res)
      }).catch(err=> {
        reject(err)
      });

  })
}

//Lot开始和结束
export function processMPCPs(config) {
  return new Promise((resolve,reject)=>{
    const { U_MPCO, U_MEQG, U_MEQU, U_MLOO, U_OperParm, product_mat_id, product_qty='',product_inqty='', keepfq=false} = config

    var _tables = '<MPCP><U_MPCO>'+U_MPCO+'</U_MPCO><U_MEQU>'+U_MEQU+'</U_MEQU>'

    if(U_OperParm == 'Y')
    {
      _tables += '<U_OperParm>skipsh</U_OperParm>'
    }

    if(U_MPCO == 'end' && keepfq){
      _tables += '<U_OperParm>keepfq</U_OperParm>'
    }

    _tables += '<MPCP1>'
    U_MLOO.forEach(item=>{
      _tables += '<row><U_MLOO>'+item+'</U_MLOO></row>'
    })
     _tables += '</MPCP1></MPCP>'

    var _key = ''

    var _param ={
        'id':'U2',
        'tables':encodeURIComponent(_tables),
        'key': _key
      }

    // if(product_mat_id != '' && product_qty != ''){
    //   var _table1 = '<MLOO><U_Qty>'+product_qty+'</U_Qty><U_ItemCode>'+product_mat_id+'</U_ItemCode></MLOO>'
    //   _param.tables1 = encodeURIComponent(_table1)
    //   _param.id1 = '-1'
    //   _param.key1 = U_MLOO[0]
    // }

    console.log('processMPCPs receive para:',_param)

    updateCommonDao(_param).then(res=>{

        console.log('processMPCPs receive result:',res)
        if(U_MPCO == 'run'){

          if(U_MEQG == 'HJ' || U_MEQG == 'TB'){

            if(product_mat_id != ''){

              U_MLOO.forEach(item=>{
                var _table1 = '<MLOO><U_ItemCode>'+product_mat_id+'</U_ItemCode></MLOO>'

                console.log('MLOO------para',U_MEQG,U_MPCO,item,_table1)
                updateCommonDao({
                    'id':'-1',
                    'tables':encodeURIComponent(_table1),
                    'key': item
                  }).then(res=>{
                    resolve(res)
                }).catch(err=> {
                  reject(err)
                });

              })

            }
          }

        }else if(U_MPCO == 'end'){

          if(U_MEQG == 'HJ' || U_MEQG == 'TB'){

            if(product_qty != ''){
              U_MLOO.forEach(item=>{
                var _table1 = '<MLOO><U_Qty>'+product_qty+'</U_Qty>'

                if(product_inqty != ''){
                  _table1 += '<U_InQty>'+product_inqty+'</U_InQty>'
                }

                _table1 += '</MLOO>'

                console.log('MLOO------para',U_MEQG,U_MPCO,item,_table1)
                updateCommonDao({
                    'id':'-1',
                    'tables':encodeURIComponent(_table1),
                    'key': item
                  }).then(res=>{
                    resolve(res)
                }).catch(err=> {
                  reject(err)
                });

              })
            }

          }

        }


        resolve(res)
    }).catch(err=> {
      reject(err)
    });

  })
}

//设备开机(停机->待机)
export function processResStartMPCPs(config) {
  return new Promise((resolve,reject)=>{
    const { U_MEQU } = config
    var _tables = '<MPCP><U_MPCO>pendc</U_MPCO><U_MEQU>'+U_MEQU+'</U_MEQU></MPCP>'
    var _key = ''

    console.log('processMPCPs receive para:',_tables)

      updateCommonDao({
        'id':'U2',
        'tables':encodeURIComponent(_tables),
        'key': _key
      }).then(res=>{
        resolve(res)
      }).catch(err=> {
        reject(err)
      });

  })
}

//设备停机(待机->停机)
export function processResEndMPCPs(config) {
  return new Promise((resolve,reject)=>{
    const { U_MEQU } = config
    var _tables = '<MPCP><U_MPCO>pend</U_MPCO><U_MEQU>'+U_MEQU+'</U_MEQU></MPCP>'
    var _key = ''

    console.log('processMPCPs receive para:',_tables)

      updateCommonDao({
        'id':'U2',
        'tables':encodeURIComponent(_tables),
        'key': _key
      }).then(res=>{
        resolve(res)
      }).catch(err=> {
        reject(err)
      });

  })
}


function updateCommonDao(config) {
  return new Promise((resolve,reject)=>{
    const { id, tables, key='', id1='', tables1='', key1=''} = config
      var fmData = new FormData();
      fmData.append('id', id)
      fmData.append('tables', tables)
      fmData.append('key', key)
      fmData.append('_session',getSession())

      if(tables1!='' && key1 !=''){
        fmData.append('id1', id1)
        fmData.append('tables1', tables1)
        fmData.append('key1', key1)
      }

      axios({
        method: "post",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        url: (baseDBName == 'MesTest' ? baseUrl : '') + "/api/Udi?_db="+baseDBName,  //baseUrl+
        data: fmData,
      }).then(resData => {
        console.log('update Common API!!',resData);
          resolve(resData)
      }).catch(err=> {
        console.log('error Common API!!',err.response);
        if(err.response.data == 'session overtime'){
          store.dispatch('user/logout')
          router.push(`/login?redirect=${router.fullPath}`)
        }else{
          reject(err.response.data)
        }
      });
  })
}

function updateCommonDaoU1(config) {
  return new Promise((resolve,reject)=>{
    const { id1, tables1, key1=''} = config
      var fmData = new FormData();
      fmData.append('id1', id)
      fmData.append('tables1', tables)
      fmData.append('key1', key)
      fmData.append('_session',getSession())

      axios({
        method: "post",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        url: (baseDBName == 'MesTest' ? baseUrl : '') + "/api/Udi?_db="+baseDBName,  //baseUrl+
        data: fmData,
      }).then(resData => {
        console.log('update Common API!!',resData);
          resolve(resData)
      }).catch(err=> {
        console.log('error Common API!!',err.response);
        if(err.response.data == 'session overtime'){
          store.dispatch('user/logout')
          router.push(`/login?redirect=${router.fullPath}`)
        }else{
          reject(err.response.data)
        }
      });
  })
}

export function fetchCommonList(query) {
  return new Promise((resolve,reject)=>{
     const { fields, table, page = 1, limit = 20, session, orderby=''} = query
     const _start = (page-1)*limit + 1
      var fmData = new FormData();
      fmData.append('fields', fields)
      fmData.append('table', table)
      fmData.append('_start', _start)
      fmData.append('_limit', limit)
      fmData.append('_session', session == undefined ? getSession() : session )

      if(orderby != ''){
        fmData.append('orderby', orderby)
      }

      Object.keys(query).forEach(item=>{
        if(item.indexOf('eq_')==0 || item.indexOf('ge_')==0 || item.indexOf('le_')==0 || item.indexOf('ne_')==0){
          fmData.append(item,query[item])
        }
      })

      axios({
        method: "post",
        headers: {"Content-Type": "application/x-www-form-urlencoded"},
        url: (baseDBName == 'MesTest' ? baseUrl : '') + "/DiDao.ashx?_db="+baseDBName, //baseUrl+
        data: fmData,
      }).then(resData => {
        //console.log('get Common API!!',resData);
          resolve(resData)
      }).catch(err=> {
        console.log('error Common API!!',err.response);
        if(err.response.data == 'session overtime'){
          store.dispatch('user/logout').then(()=>{
            router.push('/login') //`/login?redirect=${router.fullPath}`
            console.log('error Common API!! session overtime',err.response,router);
          })
        }else{
          reject(err.response.data)
        }
      });
  })
}

//获取指定设备的最后一次操作明细
export function fetchSingleResMPCPDetail(config) {
  const { Code } = config
  return new Promise((resolve,reject)=>{
      fetchCommonList({
        'fields':'DocEntry,Code,Name,Canceled,U_MLOT,U_MEQG,U_VisOrder,U_LastMPCP',
        'table':'@MEQU',
        'page': 1,
        'limit': 1000
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          const _res = resData.data.filter(v=>v.Code == Code)[0]
          //console.log('fetchSingleResMPCPDetail------', _res.U_LastMPCP)
          if(_res.U_LastMPCP != undefined && _res.U_LastMPCP.length > 0){
            fetchCommonList({
              'fields':'DocEntry,LineId,U_MLOO,U_Ostate',
              'table':'@MPCP1',
              'page': 1,
              'limit': 10000
            }).then(res=>{
              const _mpcp1 = res.data.filter(v=>v.DocEntry == _res.U_LastMPCP).sort((a,b)=>a.LineId-b.LineId)
              console.log('fetchSingleResMPCPDetail------', _res.U_LastMPCP,_mpcp1)
              resolve(_mpcp1)
            }).catch(err=>{
              reject(err)
            })

          }else{
            reject('interface get wrong: the unvalid U_LastMPCP')
          }

        }else{
          reject('interface error')
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//获取熟化工程当日待生产的批次
export function fetchSHWaitingLOTs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'DocEntry,U_MEQU,CreateDate,U_OperParm',
        'table':'@MPCP',
        'page': 1,
        'limit': 9999,
        'eq_Canceled':'N',
        //'eq_U_MPCO':'end',
        //'ne_U_OperParm':'skipsh',
        'ge_CreateDate': dateAddDays(-21),
        'le_CreateDate': dateAddDays(1), //parseDate(new Date())
        'orderby':'DocEntry'
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          console.log('fetchSHWaitingLOTs--0----------',resData.data.length,resData.data)
          const _list = resData.data.filter(v=>v.U_OperParm != 'skipsh')  //.sort((a,b)=>a.DocEntry - b.DocEntry)
          console.log('fetchSHWaitingLOTs--1----------',_list.length,_list)

          if(_list.length>0){
            const _docEntrys = _list.map(v=>v.DocEntry)
            var _fromDocEntry = _list[0].DocEntry

            //console.log('fetchSHWaitingLOTs--11----------',_docEntrys,_fromDocEntry)

            var _lots = []  //批次数组
            var _pros = []  //单批次工序明细List
            var _ons = []   //是否包含G_SH ， 1是包含， 0 不包含
            var _dlots = [] //最后工序是熟化的批次
            var _mats = []  //批号与产品名称,数量数组

            fetchCommonList({
              'fields':'Code,Name,U_LastMPCP,U_Qty,U_InQty,U_ItemCode,U_Ostate',
              'table':'@MLOO',
              'page': 1,
              'limit': 9999,
              'ge_U_LastMPCP': _fromDocEntry,
              'orderby':'U_LastMPCP'
            }).then(res=>{
              if(res.status === 200 && (res.statusText==='OK' || res.statusText==='')){
                _mats = res.data

                fetchCommonList({
                  'fields':'DocEntry,LineId,U_MLOO,U_Ostate',
                  'table':'@MPCP1',
                  'page': 1,
                  'limit': 9999,
                  'ge_DocEntry': _fromDocEntry,
                  'orderby':'DocEntry'
                }).then(resData=>{
                  if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
                    //console.log('fetchSHWaitingLOTs--2----------',resData.data.length,resData.data)
                    var _mpcp1s = resData.data.filter(v=>_docEntrys.indexOf(v.DocEntry)>=0) //.sort((a,b)=>a.DocEntry - b.DocEntry)

                    _mpcp1s = _mpcp1s.filter(s=>_list.map(m=>m.DocEntry).indexOf(s.DocEntry)>=0)
                    console.log('fetchSHWaitingLOTs--3----------',_mpcp1s.length,_mpcp1s)
                    _mpcp1s.map(v=>{
                      var _idx = _lots.indexOf(v.U_MLOO)
                      var _prodInfo = {'DocEntry':v.DocEntry,'LineId':v.LineId,'U_MLOO':v.U_MLOO,'U_Ostate':v.U_Ostate}
                      var _matInfo = _mats.filter(m=>m.U_LastMPCP == v.DocEntry && m.Code == v.U_MLOO )

                      if(_matInfo.length > 0){
                        _prodInfo.U_ItemCode = _matInfo[0].U_ItemCode
                        _prodInfo.U_Qty = _matInfo[0].U_Qty
                      }

                      if(_idx<0){
                        _lots.push(v.U_MLOO)
                        _pros.push([_prodInfo])

                        if(v.U_Ostate == 'G_SH'){
                          _ons.push(1)
                        }else{
                          _ons.push(0)
                        }
                      }else{
                        _pros[_idx].push(_prodInfo)

                        if(v.U_Ostate == 'G_SH'){
                          _ons[_idx] = _pros[_idx].length
                        }
                      }
                    })

                    _ons.forEach((v,idx)=>{
                      if(v > 0 && v == _pros[idx].length){
                        var _item = _pros[idx][_pros[idx].length-1]
                        var _mainmpcp = _list.filter(v=>v.DocEntry == _item.DocEntry)
                        _item.U_MEQU = _mainmpcp[0].U_MEQU
                        _item.CreateDate = _mainmpcp[0].CreateDate
                        _dlots.push(_item)
                      }
                    })
                    //console.log('fetchSHWaitingLOTs--4----------',_dlots.length,_dlots)

                    //var _curPagelist = _dlots.filter((item, index) => index < limit * page && index >= limit * (page - 1))
                    resolve(_dlots)

                  }else{
                    resolve([])
                  }

                }).catch(err=>{
                  reject(err)
                })

              }

            }).catch(err=>{
              reject(err)

            })


          }else{
            resolve([])
          }

        }else{
          resolve([])
        }
      }).catch(err=> {
        reject(err)
      });

  })
}


//获取分切工程当日待生产的批次
export function fetchFQWaitingLOTs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'DocEntry,U_MEQU,CreateDate,U_OperParm',
        'table':'@MPCP',
        'page': 1,
        'limit': 9999,
        'eq_Canceled':'N',
        //'eq_U_MPCO':'end',
        //'ne_U_OperParm':'skipsh',
        'ge_CreateDate': dateAddDays(-21),
        'le_CreateDate': dateAddDays(1),
        'orderby':'DocEntry'
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          //console.log('fetchFQWaitingLOTs--0----------',resData.data.length,resData.data)
          const _list = resData.data
          //console.log('fetchFQWaitingLOTs--1----------',_list.length,_list)

          if(_list.length>0){
            const _docEntrys = _list.map(v=>v.DocEntry)
            var _fromDocEntry = _list[0].DocEntry

          //console.log('fetchFQWaitingLOTs--11----------',_docEntrys,_fromDocEntry)

            var _lots = []  //批次数组
            var _pros = []  //单批次工序明细List
            var _ons = []   //是否包含G_FQ ， 1是包含， 0 不包含
            var _dlots = [] //最后工序是分切的批次
            var _mats = []  //批号与产品名称,数量数组

            fetchCommonList({
              'fields':'Code,Name,U_LastMPCP,U_Qty,U_InQty,U_ItemCode,U_Ostate',
              'table':'@MLOO',
              'page': 1,
              'limit': 9999,
              'ge_U_LastMPCP': _fromDocEntry,
              'orderby':'U_LastMPCP'
            }).then(res=>{
              if(res.status === 200 && (res.statusText==='OK' || res.statusText==='')){
                _mats = res.data

                fetchCommonList({
                  'fields':'DocEntry,LineId,U_MLOO,U_Ostate',
                  'table':'@MPCP1',
                  'page': 1,
                  'limit': 9999,
                  'ge_DocEntry': _fromDocEntry,
                  'orderby':'DocEntry'
                }).then(resData=>{
                  if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
                    //console.log('fetchFQWaitingLOTs--2----------',resData.data.length,resData.data)
                    var _mpcp1s = resData.data.filter(v=>_docEntrys.indexOf(v.DocEntry)>=0) //.sort((a,b)=>a.DocEntry - b.DocEntry)

                    //console.log('fetchFQWaitingLOTs--3----------',_mpcp1s.length,_mpcp1s)
                    _mpcp1s.map(v=>{
                      var _idx = _lots.indexOf(v.U_MLOO)
                      var _prodInfo = {'DocEntry':v.DocEntry,'LineId':v.LineId,'U_MLOO':v.U_MLOO,'U_Ostate':v.U_Ostate}
                      var _matInfo = _mats.filter(m=>m.U_LastMPCP == v.DocEntry && m.Code == v.U_MLOO )

                      if(_matInfo.length > 0){
                        _prodInfo.U_ItemCode = _matInfo[0].U_ItemCode
                        _prodInfo.U_Qty = _matInfo[0].U_Qty
                      }

                      if(_idx<0){
                        _lots.push(v.U_MLOO)
                        _pros.push([_prodInfo])

                        if(v.U_Ostate == 'G_FQ'){
                          _ons.push(1)
                        }else{
                          _ons.push(0)
                        }
                      }else{
                        _pros[_idx].push(_prodInfo)

                        if(v.U_Ostate == 'G_FQ'){
                          _ons[_idx] = _pros[_idx].length
                        }
                      }
                    })

                    _ons.forEach((v,idx)=>{
                      if(v > 0 && v == _pros[idx].length){
                        var _item = _pros[idx][_pros[idx].length-1]
                        var _mainmpcp = _list.filter(v=>v.DocEntry == _item.DocEntry)
                        _item.U_MEQU = _mainmpcp[0].U_MEQU
                        _item.CreateDate = _mainmpcp[0].CreateDate
                        _dlots.push(_item)
                      }
                    })
                    //console.log('fetchFQWaitingLOTs--4----------',_dlots.length,_dlots)

                    //var _curPagelist = _dlots.filter((item, index) => index < limit * page && index >= limit * (page - 1))
                    resolve(_dlots)

                  }else{
                    resolve([])
                  }

                }).catch(err=>{
                  reject(err)
                })

              }
            }).catch(err=>{
              reject(err)
            })

          }else{
            resolve([])
          }

        }else{
          resolve([])
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//获取批号,产品,数量明细
export function fetchMLOOsByDocEntry(query){
  const { minDocEntry } = query
  return new Promise((resolve,reject)=>{
    fetchCommonList({
      'fields':'Code,Name,U_LastMPCP,U_Qty,U_InQty,U_ItemCode,U_Ostate',
      'table':'@MLOO',
      'page': 1,
      'limit': 9999,
      'ge_U_LastMPCP': minDocEntry,
      'orderby':'U_LastMPCP'
    }).then(resData=>{
      if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
        resolve(resData.data)
      }
    }).catch(err=>{
      reject(err)
    })
  })
}


//获取批号,产品,数量明细
export function fetchSingleMLOOsByDocEntry(query){
  const { DocEntry } = query
  return new Promise((resolve,reject)=>{
    fetchCommonList({
      'fields':'Code,Name,U_LastMPCP,U_Qty,U_InQty,U_ItemCode,U_Ostate',
      'table':'@MLOO',
      'page': 1,
      'limit': 9999,
      'eq_U_LastMPCP': DocEntry,
      'orderby':'U_LastMPCP'
    }).then(resData=>{
      if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
        resolve(resData.data)
      }
    }).catch(err=>{
      reject(err)
    })
  })
}


//获取所有的设备清单
export function fetchList(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'DocEntry,Code,Name,Canceled,U_MLOT,U_MEQG,U_VisOrder,U_LastMPCP',
        'table':'@MEQU',
        'page': 1,
        'limit': 2000
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>a.DocEntry - b.DocEntry).map(item=>{
            item.id = item.DocEntry
            item.MEQG_Code = item.U_MEQG
            if(item.U_MEQG === 'HJ'){
              item.MEQG_Name = '混胶工程'
            }else if(item.U_MEQG === 'TB'){
              item.MEQG_Name = '涂布工程'
            }else if(item.U_MEQG === 'FQ'){
              item.MEQG_Name = '分切工程'
            }else if(item.U_MEQG === 'SH'){
              item.MEQG_Name = '熟化工程'
            }else{
              item.MEQG_Name = ''
            }

            item.scbh = item.U_MEQG.toLowerCase()+'sc'
            item.zlbh = item.U_MEQG.toLowerCase()+'zl'

            return item
          })

          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//获取所有的设备清单
export function GetMEQGByResCode(query) {
  return new Promise((resolve,reject)=>{
    const { code, type } = query
      fetchCommonList({
        'fields':'DocEntry,Code,Name,Canceled,U_MLOT,U_MEQG,U_VisOrder,U_LastMPCP',
        'table':'@MEQU',
        'page': 1,
        'limit': 20,
        'eq_Code': code,
        'eq_Canceled': 'N'
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _item = resData.data[0]
          var _zjbh = _item.U_MEQG.toLowerCase()+type
          resolve(_zjbh)
        }else{
          reject(resData)
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//获取所有的设备状态清单
export function fetchAllResStatus() {
  return new Promise((resolve,reject)=>{
      fetchCommonList({
        'fields':'DocEntry,Code,Name,Canceled,U_MLOT,U_MEQG,U_VisOrder,U_LastMPCP',
        'table':'@MEQU',
        'page': 1,
        'limit': 1000
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.filter(v=>v.Canceled==='N').sort((a,b)=>a.DocEntry - b.DocEntry).map(item=>{
            item.id = item.DocEntry
            item.MEQG_Code = item.U_MEQG
            if(item.U_MEQG === 'HJ'){
              item.MEQG_Name = '混胶工程'
            }else if(item.U_MEQG === 'TB'){
              item.MEQG_Name = '涂布工程'
            }else if(item.U_MEQG === 'FQ'){
              item.MEQG_Name = '分切工程'
            }else if(item.U_MEQG === 'SH'){
              item.MEQG_Name = '熟化工程'
            }else{
              item.MEQG_Name = ''
            }

            item.prodMatId = ''
            item.prodQty = ''

            if(item.U_MLOT == 'running' && item.U_LastMPCP != ''){
              fetchCommonList({
                'fields':'Code,U_ItemCode,U_Qty,U_InQty',
                'table':'@MLOO',
                'page': 1,
                'limit': 1000,
                'eq_U_LastMPCP': item.U_LastMPCP,
                'eq_U_Ostate': 'S_'+item.Code
              }).then(res=>{
                item.prodMatId = res.data.length>0 ? res.data[0].U_ItemCode : ''
                item.prodQty = res.data.length>0 ? res.data[0].U_Qty : ''
              })
            }

            return item
          })

          const HJList = _list.filter(v=>v.U_MEQG === 'HJ').sort((a,b)=>a.DocEntry-b.DocEntry)
          const TBList = _list.filter(v=>v.U_MEQG === 'TB').sort((a,b)=>a.DocEntry-b.DocEntry)
          const SHList = _list.filter(v=>v.U_MEQG === 'SH').sort((a,b)=>a.DocEntry-b.DocEntry)
          const FQList = _list.filter(v=>v.U_MEQG === 'FQ').sort((a,b)=>a.DocEntry-b.DocEntry)
          console.log('fetchAllResStatus-----------',[HJList,TBList,SHList,FQList])
          resolve([HJList,TBList,SHList,FQList])

        }else{
          resolve([])
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//获取所有的设备组清单
export function fetchOpers() {
  return new Promise((resolve,reject)=>{
      const config = {
        'fields':'DocEntry,Code,Name,Canceled',
        'table':'@MEQG',
        'page': 1,
        'limit': 20
      }
      console.log('fetchOpers-----config:',config)
      fetchCommonList(config).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          resolve(resData.data.filter(v => v.Canceled === 'N').sort((a,b)=>a.DocEntry -b.DocEntry))
        }else{
          resolve([])
        }
      }).catch(err=> {
        reject(err)
      });

  })
}



export function updateBOUDLs(config) {
  return new Promise((resolve,reject)=>{
    const { Code, U_Code, U_Val} = config

    var _tables = '<BOUDL><U_Code>'+U_Code+'</U_Code><U_Val>'+U_Val+'</U_Val></BOUDL>'

    updateCommonDao({
      'id':'-1',
      'tables':encodeURIComponent(_tables),
      'key': Code
    }).then(res=>{
      resolve(res)
    }).catch(err=> {
      reject(err)
    })

  })
}

//获取自定义下拉管理
export function fetchBOUDLs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'Code,Name,U_Code,U_Desc,U_Val',
        'table':'@BOUDL',
        'page': 1,
        'limit': 9000,
        'orderby':'U_Code,Code'
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data

          resolve(_list)

        }else{
          resolve([])
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//获取所有的设备参数组清单(生产参数和质检参数)
export function fetchEDCs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'DocEntry,Code,Name',
        'table':'@BOUDF',
        'page': 1,
        'limit': 2000,
        'orderby':'DocEntry'
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>a.DocEntry - b.DocEntry)

          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//获取指定设备组的所有参数清单
export function fetchEDCDetails(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20, code} = query
      fetchCommonList({
        'fields':'Code,LineId,U_Fd,U_FdType,U_Rlist,U_Rtable,U_Decim,U_IsReq,U_VisOrder',
        'table':'@BOUDF1',
        'page': 1,
        'limit': 2000
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.filter(item=>item.Code == code).sort((a,b)=>a.U_VisOrder.localeCompare(b.U_VisOrder))
          console.log('_list--------',code,_list)
          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//用户组BOUSG
export function fetchBOUSGs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'DocEntry,Code,Name,U_Menu',
        'table':'@BOUSG',
        'page': 1,
        'limit': 99999
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>a.DocEntry*1-b.DocEntry*1)
          var _curPagelist = []
          if(_list.length<=limit){
            _curPagelist = _list
          }else{
            _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          }

          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}


//用户组功能BOFUN
export function fetchBOFUNs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'Code,Name,U_BOUSG,U_Val,U_Type',
        'table':'@BOFUN',
        'page': 1,
        'limit': 99999
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>a.Code*1-b.Code*1)

          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//用户BOUSR
export function fetchBOUSRs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'DocEntry,Code,Name,U_Pwd,U_BOUSG',
        'table':'@BOUSR',
        'page': 1,
        'limit': 99999
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>a.DocEntry*1-b.DocEntry*1)

          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}


//操作绑定数据
export function fetchMLUDs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'Code,Name,U_BOUDF,U_IsReq,U_MEQG,U_MPCO',
        'table':'@MLUD',
        'page': 1,
        'limit': 99999
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>a.Code*1-b.Code*1)

          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//操作获得反面数据
export function fetchContraryMLUDByU_BOUDF(query) {
  return new Promise((resolve,reject)=>{
    const { U_BOUDF } = query
      fetchCommonList({
        'fields':'Code,Name,U_BOUDF,U_IsReq,U_MEQG,U_MPCO',
        'table':'@MLUD',
        'page': 1,
        'limit': 99999,
        'eq_U_BOUDF': U_BOUDF,
        'eq_U_IsReq': '0',
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          if(resData.data.length>0){
            resolve(resData.data[0].Code)
          }else{
            resolve('')
          }
        }else{
          reject(resData)
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//lot操作记录
export function fetchMPCPs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20, U_MEQU='',U_MPCO='',Canceled=''} = query
      fetchCommonList({
        'fields':'DocEntry,Canceled,U_MEQU,U_MPCO,U_MLOT,U_OperParm,CreateDate,CreateTime',
        'table':'@MPCP',
        'page': 1,
        'limit': 99999
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>b.DocEntry*1-a.DocEntry*1)

          if(U_MEQU != '' && U_MEQU.length>0){
            _list = _list.filter(v=>v.U_MEQU == U_MEQU)
          }

          if(U_MPCO != '' && U_MPCO.length>0){
            _list = _list.filter(v=>v.U_MPCO == U_MPCO)
          }

          if(Canceled != '' && Canceled.length>0){
            _list = _list.filter(v=>v.Canceled == Canceled)
          }

          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//lot操作记录_end
export function fetchMPCPends(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20, U_MEQU='',U_MPCO='',Canceled=''} = query
      fetchCommonList({
        'fields':'DocEntry,Canceled,U_MEQU,U_MPCO,U_MLOT,U_OperParm,CreateDate,CreateTime',
        'table':'@MPCP',
        'page': 1,
        'limit': 99999,
        'eq_U_MPCO':'end'
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>b.DocEntry*1-a.DocEntry*1)

          if(U_MEQU != '' && U_MEQU.length>0){
            _list = _list.filter(v=>v.U_MEQU == U_MEQU)
          }

          if(U_MPCO != '' && U_MPCO.length>0){
            _list = _list.filter(v=>v.U_MPCO == U_MPCO)
          }

          if(Canceled != '' && Canceled.length>0){
            _list = _list.filter(v=>v.Canceled == Canceled)
          }

          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//lot操作记录1
export function fetchMPCP1s(query) {
  return new Promise((resolve,reject)=>{
    const { DocEntry = '' } = query

      var config = {
        'fields':'DocEntry,LineId,U_MLOO,U_Ostate',
        'table':'@MPCP1',
        'page': 1,
        'limit': 99999
      }

      if(DocEntry.length > 0){
        config['eq_DocEntry'] = DocEntry
      }

      fetchCommonList(config).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>b.DocEntry*1-a.DocEntry*1)
          resolve(_list)

        }else{
          resolve([])
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//_lot操作对象
export function fetchMLOOs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20} = query
      fetchCommonList({
        'fields':'DocEntry,Code,Name,U_Ostate,U_LastMPCP',
        'table':'@MLOO',
        'page': 1,
        'limit': 99999
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>b.DocEntry*1-a.DocEntry*1)

          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//数据表BOUDD
export function fetchBOUDDs(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20, U_BOUDF='', Canceled=''} = query
      fetchCommonList({
        'fields':'DocEntry,U_BOUDF,U_RefCode,U_RefType,U_RefEntry,Canceled,CreateDate,CreateTime',
        'table':'@BOUDD',
        'page': 1,
        'limit': 99999
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _list = resData.data.sort((a,b)=>a.DocEntry*1-b.DocEntry*1)

          if(U_BOUDF!=undefined && U_BOUDF != ''){
            _list = _list.filter(v=>v.U_BOUDF == U_BOUDF)
          }

          if(Canceled!=undefined && Canceled != ''){
            _list = _list.filter(v=>v.Canceled == Canceled)
          }

          var _curPagelist = _list.filter((item, index) => index < limit * page && index >= limit * (page - 1))
          resolve({flist:_list,curPageList:_curPagelist})

        }else{
          resolve({flist:[],curPageList:[]})
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//数据表BOUDD根据RefCode
export function GetBouddDocEntryByRefCode(query) {
  return new Promise((resolve,reject)=>{
    const { U_RefCode='',U_BOUDF='' } = query
      fetchCommonList({
        'fields':'DocEntry,U_BOUDF,U_RefCode,U_RefType,U_RefEntry,Canceled,CreateDate,CreateTime',
        'table':'@BOUDD',
        'page': 1,
        'limit': 10,
        'eq_Canceled':'N',
        'eq_U_RefCode':U_RefCode,
        'eq_U_BOUDF':U_BOUDF
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _item = resData.data
          resolve(_item.length == 0 ? '' : _item[0].DocEntry)
        }else{
          resolve('')
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//数据表BOUDD根据RefEntry
export function fetchBouddGeDocEntry(query) {
  return new Promise((resolve,reject)=>{
    const { minDocEntry } = query
      fetchCommonList({
        'fields':'DocEntry,U_BOUDF,U_RefCode,U_RefEntry',
        'table':'@BOUDD',
        'page': 1,
        'limit': 9999,
        'eq_Canceled':'N',
        'ge_U_RefEntry':minDocEntry
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          resolve(resData.data)
        }else{
          resolve([])
        }
      }).catch(err=> {
        reject(err)
      });
  })
}

//数据表BOUDD根据RefEntry
export function GetBouddDocEntryByRefEntry(query) {
  return new Promise((resolve,reject)=>{
    const { U_RefEntry='',U_BOUDF='' } = query
      fetchCommonList({
        'fields':'DocEntry,U_BOUDF,U_RefCode,U_RefType,U_RefEntry,Canceled,CreateDate,CreateTime',
        'table':'@BOUDD',
        'page': 1,
        'limit': 10,
        'eq_Canceled':'N',
        'eq_U_RefEntry':U_RefEntry,
        'eq_U_BOUDF':U_BOUDF
      }).then(resData=>{
        if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
          var _item = resData.data
          resolve(_item.length == 0 ? '' : _item[0].DocEntry)
        }else{
          resolve('')
        }
      }).catch(err=> {
        reject(err)
      });

  })
}

//数据表行BOUDD1
export function fetchBOUDD1s(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20, U_BOUDF = '',DocEntry = '',U_RefEntry='', contraryU_BOUDF=''} = query
    console.log('fetchBOUDD1s-----', query)
    var config = {
        'fields':'Code,LineId,U_Fd,U_FdType,U_Rlist,U_Rtable,U_Decim,U_IsReq,U_VisOrder',
        'table':'@BOUDF1',
        'page': 1,
        'limit': 2000
      }

      if(U_BOUDF != ''){
        config.eq_Code = U_BOUDF
      }

        fetchCommonList(config).then(resData=>{
          if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
            var _boufds = resData.data.map(v=>{
              v.U_FdType = v.U_FdType.substring(0,1)
              v.U_FdTypeSrc = 'U_'+v.U_FdType
              v.val = ''
              return v
            })

            _boufds = _boufds.sort((a,b)=>a.U_VisOrder.localeCompare(b.U_VisOrder))

            var _cols = _boufds.map(v=>v.U_Fd)
            _cols.unshift('DocEntry')

            fetchCommonList({
              'fields':'DocEntry',
              'table':'@BOUDD',
              'page': 1,
              'limit': 999,
              'eq_U_BOUDF': U_BOUDF,
              'eq_U_RefEntry': U_RefEntry,
              'eq_U_RefType': 'T'+U_BOUDF,
              //'orderby':'DocEntry'
            }).then(resData=>{
              if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){

                const _docentry = resData.data.length>0 ? resData.data[0].DocEntry : ''

                fetchCommonList({
                  'fields':'DocEntry,LineId,U_A,U_B,U_D,U_N,U_Fd',
                  'table':'@BOUDD1',
                  'page': 1,
                  'limit': 99999,
                  'eq_DocEntry': _docentry
                }).then(resData=>{
                  if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
                    var _list = resData.data
                    //console.log('fetchCommonList_@BOUDD1:'+_list)

                    _boufds.forEach(boufd=>{
                      boufd.DocEntry = _docentry
                      _list.forEach(item=>{
                        if(boufd.U_Fd == item.U_Fd){
                          boufd.U_LineId = item.LineId
                          boufd.val = item[boufd.U_FdTypeSrc]
                          if(boufd.U_FdType == 'B' && boufd.U_Decim != ''){
                            boufd.val = (boufd.val*1).toFixed(boufd.U_Decim)
                          }
                        }
                      })
                    })

                    let clist = []
                    let _docEntry = ''
                    let _item = {}
                    _boufds.forEach((v,idx)=>{
                      if(_docEntry == '' || _docEntry != v.DocEntry){
                        _docEntry = v.DocEntry
                        _item.DocEntry = v.DocEntry
                      }
                      if(_item.DocEntry =='' && _docentry == ''){
                        _item.DocEntry = '1+'
                      }

                      _item[v.U_Fd] = v.val
                      if(v.DocEntry != _docEntry || idx == _boufds.length-1){
                        clist.push(_item)
                      }
                    })

                    resolve({
                      cols:_boufds,
                      contents:clist
                    })
                  }
                }).catch(err=> {
                  reject(err)
                });

              }
            })

          }else{
            resolve([])
          }
        }).catch(err=> {
          reject(err)
        });

  })
}

//数据表行BOUDD1
export function fetchContraryBOUDD1s(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20, U_BOUDF = '',DocEntry = '',U_RefEntry='', contraryU_BOUDF=''} = query
    console.log('fetchBOUDD1s-----', query)
    var config = {
        'fields':'Code,LineId,U_Fd,U_FdType,U_Rlist,U_Rtable,U_Decim,U_IsReq,U_VisOrder',
        'table':'@BOUDF1',
        'page': 1,
        'limit': 2000
      }

      if(U_BOUDF != ''){
        config.eq_Code = U_BOUDF
      }

        fetchCommonList(config).then(resData=>{
          if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
            var _boufds = resData.data.map(v=>{
              v.U_FdType = v.U_FdType.substring(0,1)
              v.U_FdTypeSrc = 'U_'+v.U_FdType
              v.val = ''
              return v
            })

            _boufds = _boufds.sort((a,b)=>a.U_VisOrder.localeCompare(b.U_VisOrder))

            var _cols = _boufds.map(v=>v.U_Fd)
            _cols.unshift('DocEntry')

            fetchCommonList({
              'fields':'DocEntry',
              'table':'@BOUDD',
              'page': 1,
              'limit': 999,
              'eq_U_BOUDF': U_BOUDF,
              'eq_U_RefEntry': U_RefEntry,
              'eq_U_RefType': contraryU_BOUDF,
              'orderby':'DocEntry'
            }).then(resData=>{
              if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){

                const _docentry = resData.data.length>0 ? resData.data[0].DocEntry : ''

                config = {
                  'fields':'DocEntry,LineId,U_A,U_B,U_D,U_N,U_Fd',
                  'table':'@BOUDD1',
                  'page': 1,
                  'limit': 99999,
                  'eq_DocEntry': _docentry
                }

                if(_docentry != ''){
                  //config[eq_DocEntry] = _docentry

                  fetchCommonList(config).then(resData=>{
                    if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
                      var _list = resData.data
                      //console.log('fetchCommonList_@BOUDD1:'+_list)

                      _boufds.forEach(boufd=>{
                        boufd.DocEntry = _docentry
                        _list.forEach(item=>{
                          if(boufd.U_Fd == item.U_Fd){
                            boufd.U_LineId = item.LineId
                            boufd.val = item[boufd.U_FdTypeSrc]
                            if(boufd.U_FdType == 'B' && boufd.U_Decim != ''){
                              boufd.val = (boufd.val*1).toFixed(boufd.U_Decim)
                            }
                          }
                        })

                      })

                      let clist = []
                      let _docEntry = ''
                      let _item = {}
                      _boufds.forEach((v,idx)=>{
                        if(_docEntry == '' || _docEntry != v.DocEntry){
                          _docEntry = v.DocEntry
                          _item.DocEntry = v.DocEntry
                        }
                        _item[v.U_Fd+contraryU_BOUDF] = v.val
                        _item['original'+v.U_Fd+contraryU_BOUDF] = v.val
                        v.U_Fd += contraryU_BOUDF

                        if(v.DocEntry != _docEntry || idx == _boufds.length-1){
                          clist.push(_item)
                        }
                      })

                      resolve({
                        cols:_boufds,
                        contents:clist
                      })
                    }
                  }).catch(err=> {
                    reject(err)
                  });

                }
                else{

                  resolve({
                    cols:_boufds,
                    contents:[]
                  })

                }

              }

            }).catch(err=>{
              reject(err)
            })

          }else{
            resolve([])
          }
        }).catch(err=> {
          reject(err)
        });

  })
}


export function fetchMPCPendDataByBOUDFCode(query) {
  return new Promise((resolve,reject)=>{
    const { page = 1, limit = 20, U_BOUDF,U_MEQU='',fromDate='',toDate=''} = query
      const MEQG = U_BOUDF.substring(0,2).toUpperCase()
      var cols = []
      fetchCommonList({
        'fields':'Code',
        'table':'@MEQU',
        'page': 1,
        'limit': 999,
        'eq_U_MEQG': MEQG,
        'eq_Canceled':'N',
        'orderby':'Code'
      }).then(res=>{
        const MEQUCodes = res.data.map(v=>v.Code)

        fetchCommonList({
          'fields':'DocEntry,U_MEQU,U_OperParm,CreateDate',
          'table':'@MPCP',
          'page': 1,
          'limit': 99999,
          'eq_U_MPCO':'end',
          'eq_Canceled':'N',
          'ge_CreateDate': fromDate,
          'le_CreateDate': toDate,
          'orderby':'DocEntry,CreateDate'
        }).then(resData=>{
          if(resData.status === 200 && (resData.statusText==='OK' || resData.statusText==='')){
            var mpcps = resData.data.filter(v=>MEQUCodes.indexOf(v.U_MEQU)>=0)
            //console.log('mpcps-1----mpcps--',mpcps)
            if(mpcps.length>0){
              var minMpcpDocEntry = mpcps[0].DocEntry
              var maxMpcpDocEntry = 1 + mpcps[mpcps.length-1].DocEntry*1

              ///console.log('mpcps-2---minMpcpDocEntry---',minMpcpDocEntry,maxMpcpDocEntry)
              fetchCommonList({
                'fields':'DocEntry,LineId,U_MLOO,U_Ostate',
                'table':'@MPCP1',
                'page': 1,
                'limit': 99999,
                'ge_DocEntry': minMpcpDocEntry,
                'le_DocEntry': maxMpcpDocEntry,
                'orderby':'DocEntry,LineId'
              }).then(resDt=>{
                const mpcpdetils = resDt.data
                //console.log('mpcps-3----mpcpdetils--',mpcpdetils)
                fetchCommonList({
                  'fields':'Code,U_LastMPCP,U_ItemCode,U_Qty,U_InQty',
                  'table':'@MLOO',
                  'page': 1,
                  'limit': 99999,
                  //'ge_U_LastMPCP': minMpcpDocEntry,
                  //'le_U_LastMPCP': maxMpcpDocEntry,
                  'orderby':'U_LastMPCP,Code'
                }).then(res=>{
                  const mats = res.data

                  //console.log('mpcps-4----mats--',mats)
                  fetchCommonList({
                    'fields':'LineId,U_Fd,U_FdType,U_Decim,U_IsReq,U_VisOrder',
                    'table':'@BOUDF1',
                    'page': 1,
                    'limit': 99999,
                    'eq_Code': U_BOUDF,
                    'orderby':'LineId'
                  }).then(res=>{
                    cols = res.data.sort((a,b)=>a.U_VisOrder.localeCompare(b.U_VisOrder))

                    //console.log('mpcps-5----cols--',cols)
                    fetchCommonList({
                      'fields':'DocEntry,U_BOUDF,U_RefCode,U_RefType,U_RefEntry',
                      'table':'@BOUDD',
                      'page': 1,
                      'limit': 99999,
                      'eq_U_BOUDF': U_BOUDF,
                      'eq_Canceled': 'N',
                      'ge_U_RefEntry': minMpcpDocEntry,
                      'le_U_RefEntry': maxMpcpDocEntry,
                      'orderby':'DocEntry'
                    }).then(res=>{
                      const boudds = res.data

                      //console.log('mpcps-6----boudds--',boudds)
                      if(boudds.length>0){
                        const _bouddMinDocentry = boudds[0].DocEntry
                        const _bouddMaxDocentry = 1 + boudds[boudds.length-1].DocEntry*1

                        //console.log('mpcps-7----_bouddMinDocentry--',_bouddMinDocentry,_bouddMaxDocentry)
                        fetchCommonList({
                          'fields':'DocEntry,LineId,U_A,U_B,U_D,U_N,U_Fd',
                          'table':'@BOUDD1',
                          'page': 1,
                          'limit': 99999,
                          'ge_DocEntry': _bouddMinDocentry,
                          'le_DocEntry': _bouddMaxDocentry,
                          'orderby':'DocEntry,LineId'
                        }).then(res=>{
                          const boudddetails = res.data

                          //console.log('mpcps-8----boudddetails--',boudddetails)
                          var newmpcps = []

                          mpcps.forEach(v=>{
                            var _lots = mpcpdetils.filter(m=>m.DocEntry == v.DocEntry).map(s=>s.U_MLOO)
                            v.LotID = _lots.join(",")

                            var _matInfo = mats.filter(m=>m.U_LastMPCP == v.DocEntry)

                            if(_matInfo.length == 0){
                              _matInfo = mats.filter(m=>m.Code == _lots[0])
                            }
                            v.ItemCode = _matInfo.map(s=>s.U_ItemCode).join(",")
                            v.Qty = _matInfo.map(s=>s.U_Qty).join(",")
                            v.InQty = _matInfo.map(s=>s.U_InQty).filter(m=>m.trim().length>0).join(",")

                            v.bouddInfo = boudds.filter(m=>m.U_RefEntry == v.DocEntry && m.U_RefType == ('T'+U_BOUDF))
                            v.bouddInfo2 = boudds.filter(m=>m.U_RefEntry == v.DocEntry && m.U_RefType != ('T'+U_BOUDF))
                            //LineId,U_Fd,U_FdType,U_Decim,U_IsReq,U_VisOrder

                            //v.cols = cols.map(s=>s.U_Fd)
                            var _content = {}

                            if(v.bouddInfo.length>0){
                              v.DataType = '正面'
                              var _data = boudddetails.filter(m=>m.DocEntry == v.bouddInfo[0].DocEntry)
                              cols.forEach(item=>{

                                _data.forEach(ditem=>{
                                  if(ditem.U_Fd == item.U_Fd){
                                    var U_fdTypeStr = 'U_' + item.U_FdType.substring(0,1).toUpperCase()
                                    item.val = ditem[U_fdTypeStr]
                                    if(item.U_FdType == 'B' && item.U_Decim != ''){
                                      _content[item.U_Fd] = (item.val*1).toFixed(item.U_Decim)
                                    }else{
                                      _content[item.U_Fd] = ditem[U_fdTypeStr]
                                    }

                                    //console.log('mpcps-10------',item.U_Fd,U_fdTypeStr,item.val,_content)
                                  }
                                })

                              })
                            }else{
                              cols.forEach(item=>{
                                _content[item.U_Fd] = ''
                              })
                            }

                            v.content = _content

                            newmpcps.push(v)

                            if(v.bouddInfo2.length>0){
                              var _v2 = JSON.parse(JSON.stringify(v))
                              _v2.DataType = '背面'
                              //_v2.cols = cols.map(s=>s.U_Fd)
                              var _content = {}
                              var _data = boudddetails.filter(m=>m.DocEntry == v.bouddInfo2[0].DocEntry)

                              cols.forEach(item=>{

                                _data.forEach(ditem=>{
                                  if(ditem.U_Fd == item.U_Fd){
                                    var U_fdTypeStr = 'U_' + item.U_FdType.substring(0,1).toUpperCase()
                                    item.val = ditem[U_fdTypeStr]
                                    if(item.U_FdType == 'B' && item.U_Decim != ''){
                                      _content[item.U_Fd] = (item.val*1).toFixed(item.U_Decim)
                                    }else{
                                      _content[item.U_Fd] = ditem[U_fdTypeStr]
                                    }

                                  }
                                })

                              })

                              _v2.content = _content
                              newmpcps.push(_v2)
                            }

                          })

                          resolve({'list': newmpcps,'cols':cols.map(v=>v.U_Fd)})
                        })
                      }

                    })

                  })

                })

              })
            }

          }else{
            resolve({'list': [],'cols':[]})
          }
        }).catch(err=> {
          reject(err)
        });


      })

  })
}


export function fetchTBMPCPDocEntryByMLOO(query) {
  return new Promise((resolve,reject)=>{
    const { U_MLOO } = query
    fetchCommonList({
      'fields':'DocEntry,LineId,U_MLOO,U_Ostate',
      'table':'@MPCP1',
      'page': 1,
      'limit': 9999,
      'eq_U_MLOO': U_MLOO,
      'orderby':'DocEntry'
    }).then(res=>{
      if(res.status === 200 && (res.statusText==='OK' || res.statusText==='')){
        var _list = res.data.map(v=>v.DocEntry)
        var _TBDocEntry = ''

        if(_list.length>0) {
          if(_list.length == 1){
            _TBDocEntry = _list[0]

            fetchCommonList({
              'fields':'DocEntry,U_BOUDF,U_RefCode,U_RefType,U_RefEntry,Canceled,CreateDate,CreateTime',
              'table':'@BOUDD',
              'page': 1,
              'limit': 9999,
              'eq_U_BOUDF': 'tbzl',
              'eq_U_RefEntry': _TBDocEntry
            }).then(res=>{
              if(res.status === 200 && (res.statusText==='OK' || res.statusText==='')){
                resolve(res.data.length)
              }else{
                resolve(0)
              }

            }).catch(err=>{
              reject(err)
            })

          }else{
            const _minDocEntry = _list[0]*1
            const _maxDocEntry = 1+_list[_list.length-1]*1

            fetchCommonList({
                'fields':'DocEntry,U_MEQU,CreateDate,U_OperParm',
                'table':'@MPCP',
                'page': 1,
                'limit': 9999,
                'eq_Canceled':'N',
                'eq_U_MPCO':'end',
                'ge_DocEntry': _minDocEntry,
                'le_DocEntry': _maxDocEntry,
                'orderby':'DocEntry'
              }).then(res=>{
                var _slist = res.data.map(v=>{
                  if(_list.indexOf(v.DocEntry)>=0){
                    return v.DocEntry
                  }
                })

                _slist = _slist.sort()

                _TBDocEntry = _slist[0]

                fetchCommonList({
                  'fields':'DocEntry,U_BOUDF,U_RefCode,U_RefType,U_RefEntry,Canceled,CreateDate,CreateTime',
                  'table':'@BOUDD',
                  'page': 1,
                  'limit': 9999,
                  'eq_U_BOUDF': 'tbzl',
                  'eq_U_RefEntry': _TBDocEntry
                  }).then(res=>{
                    if(res.status === 200 && (res.statusText==='OK' || res.statusText==='')){
                      resolve(res.data.length)
                    }else{
                      resolve(0)
                    }
                })
              })
          }
          }
        else{
          resolve('')
        }
      }

    }).catch(err=>{
      reject(err)
    })

  })
}

export function getTBZLisexist(query) {
  return new Promise((resolve,reject)=>{
    const { TBDocEntry } = query
    fetchCommonList({
      'fields':'DocEntry,U_BOUDF,U_RefCode,U_RefType,U_RefEntry,Canceled,CreateDate,CreateTime',
      'table':'@BOUDD',
      'page': 1,
      'limit': 9999,
      'eq_U_BOUDF': 'tbzl',
      'eq_U_RefEntry': TBDocEntry
    }).then(res=>{
      if(res.status === 200 && (res.statusText==='OK' || res.statusText==='')){
        var _list = res.data.map(v=>v.DocEntry)
        resolve(res.data.length)
      }

    }).catch(err=>{
      reject(err)
    })

  })
}
